$(document).ready(function () {
    //获取url中的参数
    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]); return null; //返回参数值
    }
    var productId = getUrlParam('productId');
    var count = getUrlParam('count');

    var urlf=document.referrer;  //之前的页面

    $("#phonenumU").on("keyup",function (e) {
        // console.log($("#phonenumU").val());
        // console.log((/^1[3|4|5|7|8]\d{9}$/.test("18569759677")));
        var phone = $("#phonenumU").val();
        if(!(/^1[3|4|5|7|8]\d{9}$/.test(phone))){
            var p = "<p id=\"textInit\"></p>"
            $("#phoneWornning").append(p);
            $("#textInit").text("电话号码格式错误");
            $("#textInit").css({"color":"red"});
            return false;
        }else {
            $("#textInit").remove();
        }
    })

    function createNewShiping() {
        console.log("value:")
        console.log($("#realnameU").val());
        $.ajax({
            type: "POST",
            cache: true,
            url:"http://"+urla+"/AddAddressServlet",
            data:{
                "receiver":$("#realnameU").val(),
                "receiver_phoneNum":$("#phonenumU").val(),
                "province":$("#provinceU").val(),
                "city":$("#cityU").val(),
                "full_address":$("#addressU").val(),
                "postCode":$("#zipU").val()
            },
                // $("#addShipping").serialize(),
            error: function(request) {
                console.log("error");
                console.log(request);
            },
            success: function(data) {
                console.log("success");
                console.log(data);
            }
        });
    }
    $("#savaNewShipping").on("click",function () {
        createNewShiping();
        window.location.reload();
    });

// 时停函数，避免访问过快导致错误
    function sleep(numberMillis) {
        var now = new Date();
        var exitTime = now.getTime() + numberMillis;
        while (true) {
            now = new Date();
            if (now.getTime() > exitTime)
                return;
        }
    }



    $.ajax({
        /*url: "./json/shipping/list.json",*/
        url: "http://"+urla+"/GetAddressListServlet",
        type: "GET",
        dataType: 'JSON',
        success: function(result){
            console.log(result);
            var shippingId;
            /*var $formGroup=$("<form action='' method='POST' id='formGroup'></form>");*/
            if($.isEmptyObject(result)){
                $("#orderSub").attr("disabled","disabled");
            }
                $.each(result,function(x,obj){
                    var $input=$("<label for='check"+obj.address_id+"' class='radio_label'>" +
                        "<input type='radio' name='ads' class='radio' value='' id='check"+obj.address_id+"'></label>");
                    var $span=$("<span class='glyphicon glyphicon-map-marker'></span>");
                    var $div=$("<div class='address-info'></div>");
                    var $li=$("<li class='address-box'></li>");
                    var $span1=$("<span>收货人："+obj.receiver+"</span>");
                    var $span2=$("<span class='pull-right'>"+obj.receiver_phoneNum+"</span>");
                    var $p=$("<p class='address'>收货地址： "+obj.province+" "
                        +obj.city+" "+obj.full_address+"</p>");
                    $div.append($span1,$span2,$p);
                    $li.append($input,$span,$div);
                    /*$formGroup.append($li);*/
                    $(".address-list").append($li);

                    $("#check" + obj.address_id).click(function () {
                        var isChecked = $(this).prop("checked");
                        $(this).prop("checked", isChecked);
                        if ($(this).is(':checked')) {
                            console.log(obj.address_id + "ok");
                            shippingId=obj.address_id;
                        } else {
                            console.log(obj.address_id + "no");
                        }
                    });
                });
            /*$(".address-box:nth-child(1) input").attr("checked","checked");*/
            $("input[type='radio'][name='ads']:eq(0)").click();
            $("input[type='radio'][name='ads']:eq(0)").click();
            $(".address-box:nth-child(1) label").attr("class","radio_label checked");
            //单项商品提交

            //购物车提交
            $("#orderSub").on("click",function (event) {
                /*$.ajax({
                    type: "POST",
                    cache: true,
                    url:"http://"+urla+"/order/create.json",
                    data:"shippingId="+shippingId,
                    error: function(request) {
                        console.log("error");
                        console.log(request);
                    },
                    success: function(data) {
                        console.log("success");
                        console.log(data);
                        window.location.replace("order_pay.html?orderNo="+data.data.orderNo);
                    }
                });*/
                if (urlf.indexOf('cart.html')>=0){
                    postCartItem(shippingId);
                }else{
                    postSingleItem(shippingId);
                }
            });
            //给所有的单选按钮点击添加处理
            $("input[type='radio']").click(function(){
                //找出和当前name一样的单选按钮对应的label，并去除选中的样式的class
                $("input[type='radio'][name='"+$(this).attr('name')+"']").parent().removeClass("checked");
                //给自己对应的label
                $(this).parent().addClass("checked");
            });
        },
        error:function (data) {
            console.log(data);
        }
    });

    function postCartItem(shippingId) {
        $("div [class = 'nameCon']")
        // console.log($("div [class = 'nameCon']"));
        var goodList = $("div [class = 'nameCon']")
        var idList = "";
        for (let i = 0; i < goodList.length; i++) {
            // goodList[i]
            idList = idList+goodList[i].id+","
        }
        console.log(idList);
        $.ajax({
            type: "POST",
            cache: true,
            url:"http://"+urla+"/CreatOrderFromCartServlet",
            data: {
                "shippingId":shippingId,
                "idList":idList,
            },
            dataType:"json",
            error: function(request) {
                console.log("error");
                console.log(request);
            },
            success: function(data) {
                console.log("success");
                console.log(data);
                console.log(data.order_id);
                window.location.replace("order_pay.html?orderNo="+data.order_id);
            }
        });
    }

    function postSingleItem(shippingId) {
        // console.log($(".nameCon").attr("id"));
        $.ajax({
            type: "POST",
            cache: true,
            url:"http://"+urla+"/CreatOrderFromSingleItemServlet",
            data:{
                "shippingId":shippingId,
                "productId":productId,
                "count":count,
            },
            dataType:"json",
            error: function(request) {
                console.log("error");
                console.log(request);
            },
            success: function(data) {
                console.log("success");
                console.log(data);
                window.location.replace("order_pay.html?orderNo="+data.order_id);
            }
        });
    }


    if (urlf.indexOf('cart.html')>=0){
        showCartItem();
    }else{
        showSingleItem();
    }

    function showSingleItem() {
        $.ajax({
            /*url: "./json/order/cart-checked-product.json",*/
            url: "http://"+urla+"/CheckSingleItemServlet",
            type: "GET",
            data:{
                "id":productId,
                "count":count,
            },
            dataType: 'JSON',
            success: function(result){
                var totalPrice=0;
                // console.log(result);
                    $.each(result,function(x,obj){
                        var $i1=$("<div class='i1'><div class='ck'><div class='w-chkbox'></div></div></div>");
                        var $i2=$("<div class='i2'></div>");

                        var mainUrl = obj.imgUrls.split(",")[0];

                        var $pic=$("<div class='pic'><img src='"+mainUrl+"'></div>");
                        var $nameCon=$("<div class='nameCon' id='"+obj.good_id+"'><a href='item.html?id="+obj.good_id+"'>"+obj.good_name+"</a></div>");
                        var $i3=$("<div class='i3'><span>¥</span><span>"+obj.good_price+"</span></div>");
                        var $i4=$("<div class='i4'><span>"+count+"件</span></div>");
                        totalPrice = count*obj.good_price;
                        var $i5=$("<div class='i5'><p class='c-price'><span>¥</span><span>"+totalPrice+"</span></p></div>");
                        var $cartitem=$("<div class='cart-item'></div>");
                        $i2.append($pic,$nameCon);
                        $cartitem.append($i1,$i2,$i3,$i4,$i5);
                        $(".cart-group").append($cartitem);
                    });
                $("#priceNum").text(totalPrice);
            },
            error:function (data) {
                console.log(data);
            }
        });
    }
    
    function showCartItem() {
        $.ajax({
            /*url: "./json/order/cart-checked-product.json",*/
            url: "http://"+urla+"/GetCheckedCartServlet",
            type: "GET",
            dataType: 'JSON',
            success: function(result){
                var realPay = 0;
                console.log(result);
                $.each(result[0],function(i,item){
                    $.each(item,function(x,obj){
                        var $i1=$("<div class='i1'><div class='ck'><div class='w-chkbox'></div></div></div>");
                        var $i2=$("<div class='i2'></div>");
                        var mainUrl = obj.imgUrls.split(",")[0];
                        var $pic=$("<div class='pic'><img src='"+mainUrl+"'></div>");
                        var $nameCon=$("<div class='nameCon' id='"+obj.good_id+"'><a href='#'>"+obj.good_name+"</a></div>");
                        var $i3=$("<div class='i3'><span>¥</span><span>"+obj.good_price+"</span></div>");
                        var good_amount = result[1][i].good_amount;
                        var $i4=$("<div class='i4'><span>"+good_amount+"件</span></div>");
                        var totalPrice = obj.good_price*good_amount;
                        realPay = realPay+totalPrice;
                        var $i5=$("<div class='i5'><p class='c-price'><span>¥</span><span>"+totalPrice+"</span></p></div>");
                        var $cartitem=$("<div class='cart-item'></div>");
                        $i2.append($pic,$nameCon);
                        $cartitem.append($i1,$i2,$i3,$i4,$i5);
                        $(".cart-group").append($cartitem);
                    });
                });
                $("#priceNum").text(realPay);
            },
            error:function (data) {
                console.log(data);
            }
        });
    }
});